/***************************************************************************
 *   TCP/IP client socket SDL_RWops test                                   *
 *                                                                         *
 *   Copyright (C) 2004 by Tyler Montbriand                                *
 *   tsm@accesscomm.ca                                                     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <SDL/SDL.h>
#include <SDL/SDL_thread.h>

#ifdef __APPLE__
#include "SDL_net.h"
#else
#include <SDL/SDL_net.h>
#endif

#include "SDL_rwfd.h"
#include "SDL_rwprintf.h"
#include "SDL_rwsock.h"

int running=2;
int threadread(void *vsock),threadwrite(void *vsock);

int main(int argc, char *argv[])
{
  SDL_RWops *s;
  SDL_Init(0);
  SDLNet_Init();

  s=SDL_RWFromHost("smtmuck.dyndns.org",8888);
  if(s==NULL)
  {
    rwprintf(rwerr,"Couldn't open socket\n");
    SDLNet_Quit();
    SDL_Quit();
    return(1);
  }

  SDL_CreateThread(threadwrite,s);
  SDL_CreateThread(threadread,s);

  while(running)
    SDL_Delay(100);

  SDLNet_Quit();
  SDL_Quit();
  return(0);
}

int threadread(void *vsock)
{
  SDL_RWops *sock=(SDL_RWops *)vsock;
  while(running)
  {
    char buf[512];
    int size=SDL_RWread(sock,buf,1,512);
    if(size>0) SDL_RWwrite(rwout,buf,1,size);
    else break;
  }

  rwprintf(rwerr,"Read thread exiting, hit ENTER to quit\n");
  running--;
  return(1);
}

int threadwrite(void *vsock)
{
  SDL_RWops *sock=(SDL_RWops *)vsock;
  while(running>1)
  {
    char buf[512];
    int size=SDL_RWread(rwin,buf,1,512);
    if(size>0) SDL_RWwrite(sock,buf,1,size);
    else if(size<=0) break;
  }

  rwprintf(rwerr,"Write thread exiting\n");
  running--;
  return(1);
}
